var jwt = require('json-web-token');
var httpReq = require('superagent');
var config = require('../config.js');

var apiCallError = {
	ret: 401,
	msg: 'Internal request failed.'
};
var tokenTimeoutError = {
	ret: 405,
	msg: 'token is expiration'
};

function apiCall(url, params, callBack) {
	console.log('|*** API call **');
	console.log('|* url: ' + url);
	console.log('|* params: ' + JSON.stringify(params));

	httpReq.post(url)
	.query(params)
	.end(function (err, res) {
		if (!err && res.body) {
			console.log('|* api res: ' + JSON.stringify(res.body));
		}
		console.log('|***************');
		if (err) {
			callBack(err, null);
		} else {
			callBack(err, res.body);
		}
	});
}

function main(component, token, params, callBack) {
	var cpn = config.getComponent(component);

	console.log(params);

	if (token) {
		/**
		 * 有token,先检查
		 */
		jwt.decode(config.secretKey, token, function (err, userInfo, decodeHeader) {
			if (err) {
				console.log('| token parse error.');
				callBack({
					ret: 400,
					msg: 'token parse error.'
				});
			} else {
				var now = (new Date()).getTime();
				if (now - userInfo.exp > config.timeout) {
					console.log('| token expiration');
					callBack(tokenTimeoutError);
				} else {
					params.userid = userInfo.userid;
					apiCall(cpn.url, params, function (err, res) {
						if (err) {
							callBack(apiCallError);
						} else {
							callBack(res);
						}
					});
				}
			}
		});
	} else {
		/**
		 * 无token,登陆
		 */
		if (cpn.signInApi == params.service) {

			apiCall(cpn.url, params, function (err, res) {
				if (err) {
					callBack(apiCallError);
				} else {
					if (res.data.userid >= 0) {
						var userInfo = {
							exp: (new Date()).getTime(),
							userid: res.data.userid,
							component: component
						};
						jwt.encode(config.secretKey, userInfo, function (err, token) {
							if (err) {
								console.log('| jwt error: ' + JSON.strinify(err));
								callBack({ 
									ret: 401, 
									msg: 'get token fail.'
								});
							} else {
								callBack({
									ret: 200,
									msg: '',
									token: token
								})
							}
						});
					} else {
						callBack({ 
							ret: 401, 
							msg: 'No match any user.'
						});
					}	
				}
			});	

		} else {
			var noNeedToken = false;

			for (var i = 0; i < cpn.noNeedToken.length; i++) {
				if (cpn.noNeedToken[i] == params.service) {
					noNeedToken = true;
				}
			}

			if (noNeedToken) {
				apiCall(cpn.url, params, function (err, res) {
					if (err) {
						callBack(apiCallError);
					} else {
						callBack(res);
					}
				});
			} else {
				callBack({
					ret: 400,
					msg: 'token missing'
				});
			}
		}
	}
}

module.exports = {
	main: main	
};

